/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.cluster.impl;

import java.util.concurrent.ThreadFactory;

import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.sabayframework.cluster.ComputerId;
import org.sabayframework.cluster.NodeExecutionQueue;
import org.sabayframework.cluster.NodeMapping;
import org.sabayframework.cluster.Processor;
import org.sabayframework.cluster.ProcessorId;


public class LocalProcessor extends BaseNode<ProcessorId, ComputerId> implements Processor {
	private static final Log log = LogFactory.getLog(LocalProcessor.class);
	
	private final ProcessorExecutionQueue queue;
	private SingleNodeMapping mapping;
	
	public LocalProcessor(ProcessorId id, ThreadFactory threadFactory, int maxPollLatencyMillis) {
		super(id, id.getComputerId());
		queue = new ProcessorExecutionQueue(id.getProcessorNo(), threadFactory, maxPollLatencyMillis);
		mapping = new SingleNodeMapping(id);
	}
	
	@Override
	public NodeMapping getChildrenMapping() {
		return mapping;
	}

	@Override
	public ProcessorId getProcessorId() {
		return id;
	}

	public void start(){
		if(!queue.isActive()){
			queue.start(1);
		}
		if(log.isDebugEnabled()) log.debug(getId()+" started.");
	}
	
	public void stop(){
		if(queue.isActive()){
			queue.stop();
		}
		if(log.isDebugEnabled()) log.debug(getId()+" stopped.");
	}

	@Override
	public NodeExecutionQueue getExecutionQueue() {
		return queue;
	}	

}
